<script setup lang="ts">
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { signInfoType } from '@/utils/types'
  import information from '@/components/information/index.vue'
  import { formValidate, msg, phoneCode } from '@/utils/tools'
  import { getEventsItemTree, getIsMechanism,
    personalRegistry,
    personOrderInfo
  } from '@/api/training'
  const bottomPadding = (uni.getSystemInfoSync().screenHeight as number) - (uni.getSystemInfoSync().safeArea.bottom as number)
  const projectName = ref('')
  const agreeToExplain = ref(false)
  const columnsList = ref([])
  const isMechanism = ref(false)
  const eventsNumberNameSelect = ref('')
  const signFrom = ref<signInfoType>({
    id: 0,
    eventsId:'',
    eventsItemIds:[],
    name:'',
    sex:'',
    idCard:'',
    height:'',
    weight:'',
    pubIfHealthEnum:'',
    projectName:'',
    clothingSize:'',
    shoeSize:'',
    mobile:'',
    emergencyContact:'',
    emergencyContactPhoneNumber:'',
    cityId:'',
    provinceId:'',
    countyId:'',
    address:'',
    personalHonor:'',
    recommendedCoach:'',
    recommendedInstitutions:'',
    eventsNumberId:''
  })
  const signFromRule = {
    name:{message:'请输入姓名'},
    sex:{message:'请选择性别'},
    idCard:{message:'请输入身份证信息',patternType:'idCard'},
    height:{message:'请输入身高'},
    weight:{message:'请输入体重'},
    pubIfHealthEnum:{message:'请选择是否健康'},
    address:{message:'请输入详细地址'},
    clothingSize:{message:'请选择衣服尺码'},
    shoeSize:{message:'请选择鞋子尺码'},
    cityId:{message:'请选择所在城市'}
  }
  const signFromRuleTwo = {
    name:{message:'请输入姓名'},
    sex:{message:'请选择性别'},
    idCard:{message:'请输入身份证信息',patternType:'idCard'},
    height:{message:'请输入身高'},
    weight:{message:'请输入体重'},
    pubIfHealthEnum:{message:'请选择是否健康'},
    address:{message:'请输入详细地址'},
    clothingSize:{message:'请选择衣服尺码'},
    shoeSize:{message:'请选择鞋子尺码'},
    mobile:{message:'请输入联系方式',patternType:'phone'},
    emergencyContact:{message:'请输入紧急人'},
    emergencyContactPhoneNumber:{message:'请输入紧急联系方式',patternType:'phone'},
    cityId:{message:'请选择所在城市'}
  }



  onLoad((options:any) => {
    let params = {
      projectName:'',
      eventsId:'',
      eventsItemIds:[],
      eventsNumberId:[],
      orderId:'',
      mechanism:'',
      eventsNumberNameSelect:''
    }
    if(options.params) {
      params = JSON.parse(decodeURIComponent(options.params))
    }
    projectName.value = params.projectName
    eventsNumberNameSelect.value = params.eventsNumberNameSelect
    signFrom.value.eventsId = params.eventsId
    signFrom.value.eventsItemIds = params.eventsItemIds
    signFrom.value.eventsNumberId = params.eventsNumberId

    if(params.orderId){
      getPersionalFrom(params.orderId)
    }
    if(params.eventsId){
      projectChange(params.eventsId)
    }

    // 判断是否机构报名
    getIsMechanism().then(res => {
      if(res.code === 200){
        isMechanism.value = res.data
      }
    })

  })

  const getPersionalFrom = (data:any) => {
    personOrderInfo({id:data}).then(res => {
      if(res.code == 200){
        for(let key in signFrom.value){
            signFrom.value[key] = res.data[key]
        }
        if(res.data.eventsItems.length > 0){
          signFrom.value.eventsItemIds = res.data.eventsItems.map((item:any) => {
            return item.id
          })
        }
        signFrom.value.eventsItemIds = signFrom.value.eventsItemIds ? signFrom.value.eventsItemIds : []
        projectName.value = res.data.eventsName + '--' + res.data.itemName
        eventsNumberNameSelect.value = res.data.eventsNumberName
      }
    })
  }
  const agreeChange = (e:any) => {
    if(agreeToExplain.value){
      agreeToExplain.value = false
    }else{
      registrationNotice()
    }
  }
  const formDataInfo = ref({})
  const personalClick = async (statusEnum:number) => {
    formDataInfo.value = JSON.parse(JSON.stringify(signFrom.value))
    formDataInfo.value.registrationReviewStatusEnum = statusEnum
    if(statusEnum == 1) {
      if (!agreeToExplain.value) {
        msg('请先阅读并同意《报名须知》')
        return false
      }
    }
    if(isMechanism.value){
      await formValidate(signFrom.value, signFromRule)
    }else{
      await formValidate(signFrom.value, signFromRuleTwo)
    }
    if(formDataInfo.value.mobile && !phoneCode(formDataInfo.value.mobile)){
      msg('请输入正确的联系电话',false)
      return false
    }
    if(formDataInfo.value.emergencyContactPhoneNumber && !phoneCode(formDataInfo.value.emergencyContactPhoneNumber)){
      msg('请输入正确的紧急联系方式',false)
      return false
    }

    if(columnsList.value.length > 0 && formDataInfo.value.eventsItemIds.length == 0){
      msg('请选择报名的子项目',false)
      return false
    }
    if (statusEnum === 1) {
      confirmFromShow.value = true
      setConfirmFromTime()
    } else {
      submitRequest()
    }
  }
  const submitRequest = () => {
    personalRegistry(formDataInfo.value).then(res => {
      if(res.code == 200){
        if(formDataInfo.value.id && formDataInfo.value.id != 0){
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2];
          uni.navigateBack({
            delta:1,
            success:() => {
              // #ifndef H5
              prevPage?.$vm?.reload()
              // #endif
              // #ifdef H5
              prevPage.$.setupState.reload()
              // #endif
            }
          })
        }else{
          uni.redirectTo({url:'/pageSignUp/orderFormSign/orderFormSign'})
        }
      }
    })
  }
  const informationChange = (e:any) => {
    if(e.type == 'cityId'){
      confirmCounty.value = `${e.idList[0].text}/${e.idList[1].text}/${e.idList[2].text}`
      if(e.idList[0]){
        signFrom.value.provinceId = e.idList[0].value
      }
      if(e.idList[1]){
        signFrom.value.cityId = e.idList[1].value
      }
      if(e.idList[2]){
        signFrom.value.countyId = e.idList[2].value
      }
    }
  }

  const getAge = (str:string) => {
    if(!str){
      return str
    }
    const toStr = str.toString()
    const yearStr = toStr.substring(6, 10)
    const dateStr = `${toStr.substring(10, 12)}-${toStr.substring(12, 14)}`
    const birthday = `${yearStr}-${dateStr}`
    const birth = new Date(birthday)
    const today = new Date()
    let age = today.getFullYear() - birth.getFullYear()
    if (
      today.getMonth() < birth.getMonth() ||
      (today.getMonth() == birth.getMonth() && today.getDate() < birth.getDate())
    ) {
      age--
    }
    return  age
  }

  // 查看报名须知
  const registrationNotice = () => {
    uni.navigateTo({
      url:`/pageSignUp/personalSignUp/registrationNotice?id=${signFrom.value.eventsId}`
    })
  }
  const agreeNotice = () => {
    agreeToExplain.value = true
  }

  const changeTwoFun = (e:any,ids:any[]) => {
    if(ids.length >= 2 && !e.active){
      msg('该项目只能选择两项参加')
      return false
    }
    if(!signFrom.value.idCard){
      msg('请先填写身份证')
      return false
    }else{
      const age = getAge(signFrom.value.idCard)
      if(age > e.maxAge || age < e.minAge){
        msg(`您的年龄不符合，${e.title}报名年龄在${e.minAge}岁~${e.maxAge}岁之间`)
        return false
      }
      return true
    }
  }

  const projectChange = (data:any) => {
    getEventsItemTree({eventsId:data}).then(res => {
      if(res.code == 200){
        columnsList.value = res.data
      }else{
        columnsList.value = []
      }
    }).catch(err => {
      columnsList.value = []
    })
  }
  const confirmFromShow = ref(false)
  const confirmFromTime = ref(5)
  const confirmFromTimer = ref(null)
  const confirmCounty = ref('')
  const setConfirmFromTime = () => {
    confirmFromTime.value = 5
    if(confirmFromTimer.value){
      clearInterval(confirmFromTimer.value)
      confirmFromTimer.value = null
    }
    confirmFromTimer.value = setInterval(() => {
      confirmFromTime.value--
      if (confirmFromTime.value === 0){
        clearInterval(confirmFromTimer.value)
        confirmFromTimer.value = null
      }
    }, 1000)
  }

  defineExpose({agreeNotice})
</script>

<template>
  <view class="sign-up">
    <xx-title title="报名训练营"/>
    <up-notice-bar :duration="5000" text="温馨提示：请完整、准确填写学员相关信息，此信息后期会用于学员分班、训练装备购买等相关事项，请认真填写！" fontSize="12" bgColor="#F56C6C" color="#ffffff"></up-notice-bar>
    <view class="sign-body">
      <view class="sign-item">
        <view class="sign-label required">报名项目</view>
        <view class="sign-value">
          {{ projectName }}
        </view>
      </view>
      <view class="sign-item">
        <view class="sign-label required">报名期数</view>
        <view class="sign-value">
          {{ eventsNumberNameSelect }}
        </view>
      </view>


      <view class="sign-item" v-if="columnsList.length > 0">
        <view class="sign-label required">项目类型</view>
        <view class="sign-value">
          <xx-check v-model="signFrom.eventsItemIds" :disabled="true" :selectValue="signFrom.eventsItemIds" :changeTwoFun="changeTwoFun" label-name="title" value-name="id" :columns="columnsList"/>
        </view>
      </view>
    </view>

    <information :info="signFrom" :mechanism="isMechanism" @change="informationChange"/>
  </view>
  <view class="bottom-fixed" :style="{paddingBottom:`calc(${bottomPadding}px + 14rpx)`}">
    <view class="seizeASeat"></view>
  </view>
  <view class="bottom-btn" :style="{paddingBottom:`calc(${bottomPadding}px + 14rpx)`}">
    <view class="personal-tak-care">
      <view @click.capture.stop="agreeChange">
        <up-checkbox :checked="agreeToExplain"></up-checkbox>
      </view>
      我已阅读<text @click="registrationNotice">《报名须知》</text>并知晓同意
    </view>
    <view class="btn">
      <view class="personal-registration hollowedOut" @click="personalClick(0)" style="width:150rpx;margin-right: 20rpx">保存</view>
      <view class="personal-registration" @click="personalClick(1)" :class="{disabled:!agreeToExplain}">提交</view>
    </view>
  </view>
  <!--  用户确认信息填写-->
  <up-popup v-model:show="confirmFromShow" mode="center" :round="8" :safeAreaInsetBottom="false">
    <view class="popup">
      <view class="popup-head">
        确认信息
      </view>
      <view class="popup-body">
        <up-notice-bar :duration="5000" text="温馨提示：请认真核实填写学员相关信息！" fontSize="12" bgColor="#F56C6C" color="#ffffff"></up-notice-bar>
        <view class="form-body">
          <view class="form-body-item">
            <view class="label">报名项目：</view>
            <view class="value">{{ projectName }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">报名期数：</view>
            <view class="value">{{ eventsNumberNameSelect }}</view>
          </view>
          <view class="form-body-item" v-if="signFrom.eventsItemIds.length > 0">
            <view class="label">项目类型：</view>
            <view class="value">{{ signFrom.eventsItemIds }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">姓名：</view>
            <view class="value">{{ signFrom.name }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">性别：</view>
            <view class="value">{{ signFrom.sex == '1' ? '男' : '女' }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">身份证：</view>
            <view class="value">{{ signFrom.idCard }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">身高(cm)：</view>
            <view class="value">{{ signFrom.height }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">体重(kg)：</view>
            <view class="value">{{ signFrom.weight }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">是否健康：</view>
            <view class="value">{{ signFrom.pubIfHealthEnum == 1 ? '是' : '否' }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">衣服尺码：</view>
            <view class="value">{{ signFrom.clothingSize }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">鞋子尺码：</view>
            <view class="value">{{ signFrom.shoeSize }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">联系电话：</view>
            <view class="value">{{ signFrom.mobile }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">紧急联系人：</view>
            <view class="value">{{ signFrom.emergencyContact }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">紧急电话：</view>
            <view class="value">{{ signFrom.emergencyContactPhoneNumber }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">所在城市：</view>
            <view class="value">{{ confirmCounty }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">详细地址：</view>
            <view class="value">{{ signFrom.address }}</view>
          </view>
          <view class="form-body-item">
            <view class="label">个人荣誉：</view>
            <view class="value">{{ signFrom.personalHonor }}</view>
          </view>
          <view class="form-body-item" v-if="!isMechanism">
            <view class="label">推荐教练：</view>
            <view class="value">{{ signFrom.recommendedCoach }}</view>
          </view>
          <view class="form-body-item" v-if="!isMechanism">
            <view class="label">推荐机构：</view>
            <view class="value">{{ signFrom.recommendedInstitutions }}</view>
          </view>
        </view>
      </view>
      <view class="popup-foot">
        <up-button type="success" plain text="修改信息" @click="confirmFromShow = false"></up-button>
        <up-button type="success" :disabled="confirmFromTime !== 0" @click="submitRequest()" :text="`我已确认${confirmFromTime ? '(' + confirmFromTime +'s)' : ''}`"></up-button>
      </view>
    </view>
  </up-popup>
</template>

<style scoped lang="scss">
.popup{
  width: calc(100vw - 96rpx);
  height: 75vh;
  display: flex;
  flex-direction: column;
  .popup-head{
    border-bottom: 1px solid #F1F2F4;
    height: 100rpx;
    line-height: 100rpx;
    font-size: 32rpx;
    padding: 0 24rpx;
  }
  .popup-body{
    flex: 1;
    padding: 24rpx 28rpx;
    overflow: hidden;
    .form-body{
      font-size: 28rpx;
      height: 100%;
      overflow: scroll;
      &::-webkit-scrollbar{
        display: none;
      }
      .form-body-item{
        display: flex;
        justify-content: space-between;
        padding: 6rpx 0;
        .label{
          width: 160rpx;
          font-size: 28rpx;
          color: #818496;
          white-space: nowrap;
        }
        .value{
          max-width: calc(100% - 160rpx);
          font-size: 28rpx;
          color: #818496;
          text-align: right;
        }
      }
    }
  }
  .popup-foot{
    border-top: 1px solid #F1F2F4;
    display: flex;
    gap: 20rpx;
    padding: 20rpx 28rpx;
  }
}
.sign-up{
  width: 100%;
  min-height: 100vh;
  padding-top: 1rpx;
  background-color: #F5F5F5;
}
.bottom-fixed{
  padding-top: 14px;
  .seizeASeat{
    height: 138rpx;
  }
}
.sign-body{
  margin: 32rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 0 32rpx;
  .sign-item{
    padding: 24rpx 0;
    display: flex;
    align-items: flex-start;
    border-bottom: 1px solid #F5F5F5;
    &:last-child{
      border-bottom: none;
    }
    .sign-label{
      color: #505363;
      font-size: 28rpx;
      width: 160rpx;
      &.required{
        position: relative;
        padding-left: 20rpx;
        &:before{
          content: '*';
          display: block;
          position: absolute;
          color: #ff3c3c;
          top: 0;
          left: 0;
        }
      }
    }
    .sign-value{
      width: calc(100% - 160rpx);
      font-size: 28rpx;
      color: #21252E;
      font-weight: 500;
      input{
        width: 100%;
        font-weight: 500;
      }
      textarea{
        background-color: #F5F5F5;
        border-radius: 12rpx;
        box-sizing: border-box;
        font-weight: 500;
        width: 100%;
        padding:10rpx;
        height: 150rpx;
      }
    }
  }
}
.bottom-btn{
  position: fixed;
  bottom: 0;
  width: 100%;
  padding-left: 28rpx;
  padding-right: 28rpx;
  box-sizing: border-box;
  border-top: 1px solid #F1F2F4;
  padding-top: 14rpx;
  z-index: 10;
  background-color: #FFFFFF;
  .btn{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .personal-tak-care{
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #505363;
    margin-bottom: 10rpx;
    text{
      color: #1677FE;
    }
  }
  .personal-registration{
    background: #92C75B;
    color: #FFFFFF;
    border-radius: 16rpx;
    width:calc(100% - 20rpx);
    border:1rpx solid #92C75B;
    padding: 16rpx 0;
    letter-spacing: 2rpx;
    font-weight: 500;
    text-align: center;
    &.disabled{
      background-color: #E5E5E5;
      color:#818496;
      border:1rpx solid #E5E5E5;
    }
    &.hollowedOut{
      border:1rpx solid #92C75B;
      color: #92C75B;
      background-color: transparent;
    }
  }
}
</style>
